# -*- coding: utf-8 -*-
from google.appengine.ext import db
import logging

from controller.twitter import TwitterController

from model.search import Search
from model.history import History
from ydn import YahooKeywordApi

class SearchController(TwitterController):
    def create(self):
        r = Search(
            search = self.params.get('search', None),
            text = self.params.get('text', None),
            keywords = self.params.get('keywords', None),
        )
        r.put()
        self.redirect('/search')

    def destroy(self):
        r = Search.get(self.params.get('key'))
        if r is not None:
            r.delete()
        self.redirect('/search')

    def edit(self):
        rec = Search.get(self.params.get('key'))
        if rec:
            setattr(self, 'search', rec.search)
            setattr(self, 'text', rec.text)
            setattr(self, 'keywords', rec.keywords)
        else:
            setattr(self, 'search', 'Error')
            setattr(self, 'text', 'Error')
            setattr(self, 'keywords', 'Error')

    def index(self):
        """
        キーワード検索を行う
        TwitterのSearchAPIに検索をかけ、結果を取得してDataStoreに保存
        検索結果の文章をキーワードAPIに投げて、結果を取得する
        """
        query = self.params.get("q")
        logging.info(query)
        api = self.init()
        search_results = api.search(q=query)

        # YahooKeyWordApi関連の初期か
        yka = YahooKeywordApi()

        # history確認
        histories = History.all()
        history_query = histories.filter("function = ", "search").filter("option = ", query)
        history_res = history_query.fetch(1)
        # データがなければ空で登録
        if len(history_res) == 0:
            history = History()
            history.function = "search"
            history.option = query
            history.id = 1
            target_id = history.id
            history.put()
        else:
            target_id = history_res[0].id

        for search_result in search_results:
            search = Search()
            # idは大きい順に並ぶ
            search.id = search_result.id
            search.screen_name = search_result.from_user
            search.text = search_result.text
            search.query = query

            # historyのsearchの値を見て、
            # そのIDより大きいものだけ処理する
            # 大きいもののみSearchに記録。
            # 記録する前にYDN_APIでキーワード解析して記録。
            if search.id > target_id:
                logging.info("save")
                yka_res = yka.get_keywords(search.text)
                logging.info(yka_res)
                search.keywords = yka_res
                search.put()
        pass
    def new(self):
        pass

    def show(self):
        rec = Search.get(self.params.get('key'))
        if rec:
            setattr(self, 'search', rec.search)
            setattr(self, 'text', rec.text)
            setattr(self, 'keywords', rec.keywords)
        else:
            setattr(self, 'search', 'Error')
            setattr(self, 'text', 'Error')
            setattr(self, 'keywords', 'Error')

    def update(self):
        r = Search.get(self.params.get('key'))
        r.search = self.params.get('search', None)
        r.text = self.params.get('text', None)
        r.keywords = self.params.get('keywords', None)
        r.put()
        self.redirect('/search')
